package main

import (
	"crypto/aes"
	"crypto/cipher"
	"encoding/hex"
	"fmt"
	"strings"
	"study/dcdatabase"
)

func main() {
	res := dcdatabase.GetCodemain()
	for _, v := range res {
		mainen(v.Encode_code_str, v.Secert_key)
	}
}

func mainen(plaintextHex, keyHex string) {
	//plaintextHex := "41323030313131303030303030316237" // 16字节的16进制明文
	//keyHex := "000102030405060708090a0b0c0d0e0f"       // 16字节的16进制密钥

	plaintext, _ := hex.DecodeString(plaintextHex)
	key, _ := hex.DecodeString(keyHex)

	ciphertext, err := encryptAESECB(plaintext, key)
	if err != nil {
		fmt.Println("Error encrypting:", err)
		return
	}

	ciphertextHex := strings.ToUpper(hex.EncodeToString(ciphertext))
	fmt.Println("Ciphertext (in hex):", ciphertextHex)
}

func encryptAESECB(plaintext []byte, key []byte) ([]byte, error) {
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}

	ciphertext := make([]byte, len(plaintext))
	encrypter := NewECBEncrypter(block)
	encrypter.CryptBlocks(ciphertext, plaintext)

	return ciphertext, nil
}

type ecbEncrypter struct {
	block cipher.Block
}

func NewECBEncrypter(block cipher.Block) cipher.BlockMode {
	return &ecbEncrypter{block}
}

func (x *ecbEncrypter) BlockSize() int { return x.block.BlockSize() }

func (x *ecbEncrypter) CryptBlocks(dst, src []byte) {
	if len(src)%x.block.BlockSize() != 0 {
		panic("crypto/cipher: input not full blocks")
	}
	if len(dst) < len(src) {
		panic("crypto/cipher: output smaller than input")
	}
	for len(src) > 0 {
		x.block.Encrypt(dst, src[:x.block.BlockSize()])
		src = src[x.block.BlockSize():]
		dst = dst[x.block.BlockSize():]
	}
}
